package com.jahentao.integrationTest.case08.demo;

/**
 * 第一种synchronized方式死锁
 * <p>线程thread1先获取锁locka，然后在同步块里嵌套竞争锁lockb。
 * 而线程thread2先获取锁lockb，然后在同步块里嵌套竞争锁locka。
 * （此时已经被线程thread1拥有，而thread1在等待lockb，而lockb被thread2拥有，thread2在等待locka……无线循环）
 * @author jahentao
 * @date 2018-5-15
 *
 */
public class SyncDeadLock{  
    private static Object locka = new Object();  
    private static Object lockb = new Object();  
  
    public static void main(String[] args){  
        new SyncDeadLock().deadLock();  
    }  
  
    private void deadLock(){  
        Thread thread1 = new Thread(new Runnable() {  
            @Override  
            public void run() {  
                synchronized (locka){  
                    try{  
                        System.out.println(Thread.currentThread().getName()+" get locka ing!");  
                        Thread.sleep(500);  
                        System.out.println(Thread.currentThread().getName()+" after sleep 500ms!");  
                    }catch(Exception e){  
                        e.printStackTrace();  
                    }  
                    System.out.println(Thread.currentThread().getName()+" need lockb!Just waiting!");  
                    synchronized (lockb){  
                        System.out.println(Thread.currentThread().getName()+" get lockb ing!");  
                    }  
                }  
            }  
        },"thread1");  
  
        Thread thread2 = new Thread(new Runnable() {  
            @Override  
            public void run() {  
                synchronized (lockb){  
                    try{  
                        System.out.println(Thread.currentThread().getName()+" get lockb ing!");  
                        Thread.sleep(500);  
                        System.out.println(Thread.currentThread().getName()+" after sleep 500ms!");  
                    }catch(Exception e){  
                        e.printStackTrace();  
                    }  
                    System.out.println(Thread.currentThread().getName()+" need locka! Just waiting!");  
                    synchronized (locka){  
                        System.out.println(Thread.currentThread().getName()+" get locka ing!");  
                    }  
                }  
            }  
        },"thread2");  
  
        thread1.start();  
        thread2.start();  
    }  
}  

